package praktikumid.p06_k;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * File operations.
 * 
 * @author ago.luberg
 * 
 */
public class FileOperations {
	/**
	 * File to operate on.
	 */
	public static final String FILENAME = "p06_k.txt";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		writeStringToFile(FILENAME, "tere");
		System.out.println("fail kirjutatud");
		try {
			String sisu = readFileContents(FILENAME);

			System.out.println(sisu);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			System.err.println(e.getMessage());
		}
	}

	/**
	 * Reads and returns everything from file.
	 * 
	 * @param filename
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String readFileContents(String filename)
			throws FileNotFoundException {
		FileReader fr = new FileReader(filename);
		BufferedReader br = new BufferedReader(fr);
		String line;
		String contents = "";
		try {
			while ((line = br.readLine()) != null) {
				contents += line;
			}
			br.close();
			fr.close();			
			return contents;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static void writeStringToFile(String filename, String whatToWrite) {
		try {
			FileWriter fw = new FileWriter(filename);
			BufferedWriter bw = new BufferedWriter(fw);
			//bw.append(whatToWrite);
			bw.write(whatToWrite);
			//bw.newLine();
			bw.close();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*
		 * 
		 * http://tere => http://hello
		 */

	}

}
